const express = require('express');
const getToken = require("../util/getWeChatToken")
const getUserInfo = require("../util/getWeChatUserInfo")
const weChatUser = require("../model/wechatUser")
const xwoUser = require("../model/xwoUser")
const jwt = require("jsonwebtoken")
const bcrypt = require("bcrypt")
const LotteryRecord = require("../model/lotteryRecord")
const {secretKey} = require("../constant/constant");
const router = express.Router();

const header = "Bearer";

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});
//微信授权及获取用户名和open_id;
router.post("/authorization",async (req,res,next)=>{
  let token =  await getToken(req.query.code);
  try {
    if (token) {
      let {access_token,openid}= JSON.parse(token);
      let user_info = await getUserInfo(access_token,openid);
      if(user_info){
        let {nickname} = JSON.parse(user_info);
        let doc = await weChatUser.create({
          'token_id':openid,
          'username':nickname,
          'createDate': Date.now(),
        })
        if(doc){
          res.json({
            status:'0',
            msg:'登录成功',
            openid:openid
          })
        }else {
          res.json({
            status:'1',
            msg:'出现错误',
            openid:''
          })
        }
      }else {
        res.json({
          status:'1',
          msg:'userinfo请求失败',
          openid:''
        })
      }
    }else {
      res.json({
        status:'1',
        msg:'openid请求失败',
        openid:''
      })
    }
    next();
  }catch (e) {
    if (e) {
      res.status(500)
      res.json({
        status: '1',
        msg: e.message,
        openid: ''
      })
    }
  }
})
//xwo用户注册
router.post("/register",async(req,res,next)=>{
  let {username,password,phoneNumber} = req.body;
  const doc = await xwoUser.findOne({username});
  try {
    if(doc){ //已存在
      res.status(403)
      res.json({
        status:'1',
        msg:'用户名已存在',
      })
    }
    else {
      const saltRounds =10;
      bcrypt.genSalt(saltRounds,function (err,salt) {
        bcrypt.hash(password,salt,function (err,hash) {
          password = hash;
          xwoUser.create({
            'username':username,
            'password':password,
            'integral':0,
            'phoneNumber':phoneNumber
          })
          res.json({
            status:'0',
            msg:"用户注册成功",
          })
        })
      })
    }
    next()
  }catch (e) {
    if(e){
      res.json({
        status:'1',
        msg:e.message,
      })
    }
  }
})
router.post("/login",async (req,res,next)=>{
  let {username,password} = req.body;
  const doc  = await xwoUser.findOne({username});
  try{
    if(doc){
      bcrypt.compare(password,doc.password,(err,isvalid)=>{
        if(isvalid){ //合法
          let token  = jwt.sign({user:username},secretKey,{
            expiresIn: 60*60*24
          });
          res.json({
            status:'0',
            msg:'登录成功',
            token:token,
            header:header
          })
        }else {
          res.status(404);
          res.json({
            status:'1',
            msg:"密码错误",
          })
        }
      })
    }else {
      res.status(404);
      res.json({
        status:'1',
        msg:"没有该用户",
      })
    }
    next();
  }catch (e) {
    if (e) {
      res.status(500);
      res.json({
        status: '1',
        msg: e.message,
      })
    }
  }
})
router.get("/getWechatLotteryRecord",async (req,res,next)=>{
  //微信用户的中奖记录
  let token_id = req.query.token_id;
  let activity_id = req.query.activity_id;
  let doc = await LotteryRecord.find({username:token_id,activity_id:activity_id});
  try{
    if(doc){
      let prizeName = [],recordTime = [],id = [];
      doc.forEach(item=>{
        let pn = item.prizeName;
        let rt = item.recordTime;
        let id = item._id;
        prizeName.push(pn);
        recordTime.push(rt);
        id.push(id);
      })
      res.json({
        status:'0',
        msg:'返回中奖记录成功',
        prizeName:prizeName,
        recordTime:recordTime
      })
    }else {
      res.json({
        status:'0',
        msg:'没有中奖记录',
        prizeName:[],
        recordTime:[]
      })
    }
    next()
  }catch (e) {
    if(e){
      res.status(500);
      res.json({
        status:'1',
        msg:e.message
      })
    }
  }
})
router.post("/WechatLotteryRecordFillIn",async (req,res,next)=>{
  let token_id = req.query.token_id;
  let id = req.query.id;
  let location = req.query.location
  let phoneNumber = req.query.phoneNumber
  let actualName = req.query.actualName
  let doc = LotteryRecord.findOne({_id:id,username:token_id})
  try{
  if(doc){
    LotteryRecord.update({_id:id},{location:location,phoneNumber:phoneNumber,actualName:actualName},(err)=>{
      if(err){
        res.json({
          status:'1',
          msg:"填写信息失败"
        })
      }else{
      res.json({
        status:'0',
        msg:"填写信息成功"
      })
      }
    })
  }else {
    res.json({
      status:'1',
      msg:"没有该中奖记录"
    })
  }
  next();
  }catch (e) {
    if(e){
      res.status(500)
      res.json({
        status:'1',
        msg:e.message
      })
    }
  }
})
//剩下抽奖的部分以及希沃用户的填资料查询信息 这些cp一下改一改就好了
module.exports = router;
